package com.hcb.micro.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import com.hcb.micro.dto.*;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hcb.micro.controller.base.BaseControllers;
import com.hcb.micro.service.IMallService;
import com.hcb.micro.service.IOrderProductRefundService;
import com.hcb.micro.service.IOrderProductService;
import com.hcb.micro.service.IOrderService;
import com.hcb.micro.service.IOrderWeixinPayService;
import com.hcb.micro.service.IProductSellerService;
import com.hcb.micro.service.IProductService;
import com.hcb.micro.service.IQqbsAccountService;

import net.sf.json.JSONObject;

@Controller
@RequestMapping("orderProductRefund")
public class OrderProductRefundController extends BaseControllers{
	private transient final Logger logger = Logger.getLogger(getClass());
	@Autowired
	IQqbsAccountService qqbsAccountService;	
	
	@Autowired
	IOrderProductRefundService orderProductRefundService;
	
	@Autowired
	IMallService mallService;
	
	@Autowired
	IOrderProductService orderProductService;
	
	@Autowired
	IOrderWeixinPayService orderWeixinPayService;
	
	@Autowired
	IProductService productService;
	
	@Autowired
	IOrderService orderService;
	
	@Autowired
	IProductSellerService productSellerService;
	
	@RequestMapping(value = "list", method = RequestMethod.POST)
	@ResponseBody
	public String list() throws UnsupportedEncodingException {
		JSONObject json = new JSONObject();
		if (sign == 1) {
			json.put("result", "1");
			json.put("description", "请检查参数格式是否正确或者参数是否完整");
			return buildReqJsonInteger(1, json);
		}
		// 登录认证失败
		if (sign == 2) {
			json.put("result", "2");
			json.put("description", "账号未登录");
			return buildReqJsonInteger(2, json);
		}
		
		HttpSession session = request.getSession();
		Manager manager = (Manager) session.getAttribute("MANAGER");
        if(manager == null){
        	json.put("result", "1");
			json.put("description", "账号未登陆");
			return buildReqJsonObject(json);
        }
		
		JSONObject bodyInfo = JSONObject.fromObject(bodyString);
		
		Map<String,Object> para = new HashMap<>();
		if (bodyInfo.get("orderId") != null && !"".equals(bodyInfo.get("orderId"))) {
			para.put("orderId", bodyInfo.getString("orderId"));
		}
		if(bodyInfo.get("accountId") != null && !"".equals(bodyInfo.get("accountId"))) {
			para.put("accountId", bodyInfo.getString("accountId"));
		}
		if(bodyInfo.get("status") != null && !"".equals(bodyInfo.get("status"))) {
			para.put("status", bodyInfo.getString("status"));
		}
		
		if(bodyInfo.get("mallUuid") != null && !"".equals(bodyInfo.get("mallUuid"))) {
			para.put("mallUuid", bodyInfo.getString("mallUuid"));
		}
		Mall mall = mallService.selectByMallUuid(manager.getMallUuid()); 
		if(mall != null && !"商盟惠购".equals(mall.getMallName())){
			para.put("mallUuid", mall.getMallUuid());
		}
		
		if(manager.getType() == 3){
			para.put("productSellerId", manager.getProductSellerId());
		}
		
		List<OrderProductRefund> orderProductRefundListAll=orderProductRefundService.selectByPara(para);

		if(bodyInfo.get("page") != null && !"".equals(bodyInfo.get("page"))) {
			para.put("start", (Integer.valueOf(bodyInfo.getString("page"))-1)*Integer.valueOf(bodyInfo.getString("pageSize")));
		}
		if(bodyInfo.get("pageSize") != null && !"".equals(bodyInfo.get("pageSize"))) {
			para.put("size", Integer.valueOf(bodyInfo.getString("pageSize")));
		}

		List<OrderProductRefund> orderProductRefundList=orderProductRefundService.selectByPara(para);

		if(orderProductRefundList.size() <= 0){
			json.put("result", "1");
			json.put("description", "没有退货信息！");
			return buildReqJsonObject(json);
		}
		List<Map<String,String>> list = new ArrayList<>();
		for(OrderProductRefund opr:orderProductRefundList){
			
			Map<String,String> map = new HashMap<>();
			QqbsAccount account = qqbsAccountService.selectByAccountId(opr.getAccountId());
			OrderProduct opt=orderProductService.selectByPrimaryKey(opr.getOrderProductId());
			logger.info(opr.getId()+"ID");
			logger.info(opr.getAccountId()+"AccountId");
			logger.info(opr.getOrderProductId()+"OrderProductId");
			logger.info(opt.getProductId()+"ProductId");
			if(opt != null){
				Product prod=productService.selectByPrimaryKey(opt.getProductId());
				if (prod == null) {
					continue;
				}
				map.put("id", opr.getId()+"");
				map.put("productId", opt.getProductId()+"");
				map.put("orderId", opr.getOrderId()+"");
				map.put("mallName", "商盟惠购商城");
				map.put("accountId", opr.getAccountId()+"");
				map.put("realPrice", opr.getApplyMoney()+"");
				map.put("count", opr.getCount()+"");
				map.put("refundReason", URLDecoder.decode(opr.getExplain(), "UTF-8"));
				map.put("productName", opt.getShortName()+"");
				map.put("certificateNumber", opt.getCertificateNumber()+"");
				if(account!=null){
					map.put("accountNickName", account.getNickname()==null?"":account.getNickname());				
				}else{
					map.put("accountNickName", "");
				}
				
				String sellerName = "";
				Order order = orderService.selectByPrimaryKey(opr.getOrderId());
				if(order != null){
					ProductSeller ps = productSellerService.selectByPrimaryKey(order.getSellerId());
					sellerName = (ps== null?"":ps.getName());
				}
				
				map.put("sellerName", sellerName);
				//退货进度状态
				String statusString = "";
				switch(opr.getStatus()){
				case 1:
					statusString = "申请中";
					break;
				case 2:
					statusString = "待退货";
					break;
				case 3:
					statusString = "待退款";
					break;
				case 4:
					statusString = "退款成功";
					break;
				case 5:
					statusString = "退款关闭";
					break;
				case 6:
					statusString = "退款取消";
					break;
				}
				map.put("statusString", statusString);
				map.put("status", opr.getStatus()+"");
				//商品类型状态
				String prostatus = "";
				switch(prod.getType()){
				case 0:
					prostatus = "普通商品";
					break;
				case 1:
					prostatus = "套餐商品";
					break;			
				}
				map.put("prostatus", prostatus);
				
				String paymark = "";
				List<OrderWeixinPay> owpList = orderWeixinPayService.selectByOrderId(opr.getOrderId());
				if(owpList.size()>0){
					paymark = owpList.get(0).getPayMark();
				}
				map.put("paymark", paymark);
				
				list.add(map);
			}
		}
		
		session.setAttribute("ORDERLIST", list);
		
    	json.put("result", "0");
		json.put("description", "获取订单列表成功");
		json.put("list", list);
		json.put("count", orderProductRefundListAll.size());
		return buildReqJsonObject(json);
	}
	
	
	
	@RequestMapping(value = "toupdate", method = RequestMethod.POST)
	@ResponseBody
	public String toupdate() {
		JSONObject json = new JSONObject();
		if (sign == 1) {
			json.put("result", "1");
			json.put("description", "请检查参数格式是否正确或者参数是否完整");
			return buildReqJsonInteger(1, json);
		}
		// 登录认证失败
		if (sign == 2) {
			json.put("result", "2");
			json.put("description", "账号未登录");
			return buildReqJsonInteger(2, json);
		}
		
		HttpSession session = request.getSession();
		Manager manager = (Manager) session.getAttribute("MANAGER");
        if(manager == null){
        	json.put("result", "1");
			json.put("description", "账号未登陆");
			return buildReqJsonObject(json);
        }
		
		JSONObject bodyInfo = JSONObject.fromObject(bodyString);
		
		if (bodyInfo.get("id") == null ||"".equals(bodyInfo.get("id"))) {
			json.put("result", "1");
			json.put("description", "参数错误！");
			return buildReqJsonObject(json);
		}
		
		int id=bodyInfo.getInt("id");
		
		OrderProductRefund opr=orderProductRefundService.selectByPrimaryKey(id);
		opr.setStatus((byte) (opr.getStatus()+1));
		int res=orderProductRefundService.updateByPrimaryKeySelective(opr);
		if(res==1){
			if (opr.getStatus() >= 4){
				// 将退款成功的订单修改为交易结束
				Order order = orderService.selectByPrimaryKey(opr.getOrderId());
				order.setStatus((byte)4);
				orderService.updateByPrimaryKey(order);
			}
			json.put("result", "0");
			json.put("description", "保存成功！");
		}else{
			json.put("result", "1");
			json.put("description", "保存失败！");
		}
		return buildReqJsonObject(json);
	}

	@RequestMapping(value = "modifyRealPrice", method = RequestMethod.POST)
	@ResponseBody
	public String modifyRealPrice() {
		JSONObject json = new JSONObject();
		if (sign == 1) {
			json.put("result", "1");
			json.put("description", "请检查参数格式是否正确或者参数是否完整");
			return buildReqJsonInteger(1, json);
		}
		// 登录认证失败
		if (sign == 2) {
			json.put("result", "2");
			json.put("description", "账号未登录");
			return buildReqJsonInteger(2, json);
		}

		HttpSession session = request.getSession();
		Manager manager = (Manager) session.getAttribute("MANAGER");
		if(manager == null){
			json.put("result", "1");
			json.put("description", "账号未登陆");
			return buildReqJsonObject(json);
		}

		JSONObject bodyInfo = JSONObject.fromObject(bodyString);

		int right = 1;
		if(bodyInfo.get("id") == null || "".equals(bodyInfo.get("id"))){
			right = 0;
		}if(bodyInfo.get("realPrice") == null || "".equals(bodyInfo.get("realPrice"))){
			right = 0;
		}
		if(right == 0){
			json.put("result", "1");
			json.put("description", "操作失败，请检查输入的参数是否完整");
			return buildReqJsonObject(json);
		}

		OrderProductRefund opr = orderProductRefundService.selectByPrimaryKey(Integer.valueOf(bodyInfo.getString("id")));

		if(opr != null){
			opr.setApplyMoney(Float.valueOf(bodyInfo.getString("realPrice")));

			Integer rs = orderProductRefundService.updateByPrimaryKeySelective(opr);
			if(rs == 0){
				logger.info("---修改金额失败---");
				json.put("result", "1");
				json.put("description", "修改金额失败");
				return buildReqJsonObject(json);
			}else{
				logger.info("---修改金额成功---");
			}
		}

		json.put("result", "0");
		json.put("description", "修改金额成功");
		return buildReqJsonObject(json);
	}
}
